<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-button v-if="checkPermission(permissionRoles.inner_auto_grant_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加任务</el-button>
      <el-button v-if="checkPermission(permissionRoles.inner_auto_grant_pass)" :disabled="disabled" type="success" icon="el-icon-s-check" class="filter-item" @click="pass()">批量审核</el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border stripe style="width: 100%;" height="740" :cell-class-name="cellClassNameFn" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="服务器" prop="sname" width="70px" align="center"></el-table-column>
      <el-table-column label="角色ID" prop="actor_id" align="center"></el-table-column>
      <el-table-column label="角色名" prop="actor_name" align="center"></el-table-column>
      <el-table-column label="等级" prop="level" width="70px" align="center"></el-table-column>
      <el-table-column label="VIP" prop="vip" width="70px" align="center"></el-table-column>
      <el-table-column label="总充值金额" prop="amount" align="center"></el-table-column>
      <el-table-column label="总战力" prop="power" align="center"></el-table-column>
      <el-table-column label="钻石数量" prop="diamond" align="center"></el-table-column>
      <el-table-column label="剩余内币" prop="remainder_num" align="center"></el-table-column>
      <el-table-column label="发放内币数量" prop="grant_num" width="110px" align="center"></el-table-column>
      <el-table-column label="发放时间" prop="grant_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="间隔时间" prop="interval" width="70px" align="center"></el-table-column>
      <el-table-column label="发放条件" prop="grant_condition" align="center"></el-table-column>
      <el-table-column label="停止条件" prop="stop_condition" align="center"></el-table-column>
      <el-table-column label="任务状态" width="70px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusTagFilter">{{ row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.inner_auto_grant_pass) && row.status === 0" type="text" size="small" @click="pass(row)">审核</el-button>
          <el-button v-if="checkPermission(permissionRoles.inner_auto_grant_start) && row.status === 1" type="text" size="small" @click="handleChangeStatus(row, 2)">暂停</el-button>
          <el-button v-if="checkPermission(permissionRoles.inner_auto_grant_start) && (row.status === 2 || row.status === 3)" type="text" size="small" @click="handleChangeStatus(row, 1)">开启</el-button>
          <el-button v-if="checkPermission(permissionRoles.inner_auto_grant_del)" type="text" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" title="添加任务" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="角色ID" prop="actor_id">
          <el-input v-model="actorid" type="textarea" :autosize="{ minRows: 5, maxRows: 8}" placeholder="格式：角色ID" @blur="handleBlueActorId" />
        </el-form-item>
        <el-table v-loading="listLoading" :data="actorList" border>
          <el-table-column label="区服" prop="sname" align="center"></el-table-column>
          <el-table-column label="角色ID" prop="actor_id" align="center"></el-table-column>
          <el-table-column label="角色名" prop="name" align="center"></el-table-column>
          <el-table-column label="等级" prop="level" align="center"></el-table-column>
          <el-table-column label="VIP" prop="vip" align="center"></el-table-column>
          <el-table-column label="剩余钻石" prop="diamond" align="center"></el-table-column>
          <el-table-column label="充值金额" prop="recharge" align="center"></el-table-column>
          <el-table-column label="剩余内币" prop="inner" align="center"></el-table-column>
          <el-table-column label="最后登录时间" prop="last_login_date" align="center"></el-table-column>
          <el-table-column label="上次发放时间" prop="last_date" align="center"></el-table-column>
          <el-table-column label="上次发放数量" prop="last_num" align="center"></el-table-column>
          <el-table-column label="使用人" prop="used_user" align="center"></el-table-column>
        </el-table>
        <el-form-item label="代币类型" prop="recharge_mode">
          <el-select v-model="dataForm.recharge_mode" class="defaut-input">
            <el-option label="限时秘券" value="1" />
            <el-option label="秘券" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="发放数量" prop="grant_num">
          <el-input v-model="dataForm.grant_num" class="defaut-input" placeholder="填写发放内币数量" />
        </el-form-item>
        <el-form-item label="发放时间" prop="grant_dt">
          <el-date-picker v-model="dataForm.grant_dt" type="datetime" style="width: 50%" />
        </el-form-item>
        <el-form-item label="间隔时间" prop="interval">
          <el-input v-model="dataForm.interval" class="defaut-input" placeholder="填写间隔时间 单位：天" />
        </el-form-item>
        <el-form-item label="发放条件" prop="remainder_inner">
          <el-input v-model="dataForm.remainder_inner" class="text30" placeholder="填写剩余内币" />
          <el-input v-model="dataForm.remainder_gold" class="text30" placeholder="填写剩余钻石" />
        </el-form-item>
        <el-form-item label="停止条件" prop="no_login_days">
          <el-input v-model="dataForm.no_login_days" class="text30" placeholder="填写未登录天数 单位：天" />
          <el-input v-model="dataForm.jump_times" class="text30" placeholder="填写跳过次数" />
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :disabled="disabled" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getGrantJobList, handleGrantJob, deleteGrantJob, checkActor, handleGrantJobStatus, approvedJob } from '@/api/operator'

const defaultItem = {
  id: '',
  actor: [],
  recharge_mode: '1',
  grant_num: '',
  grant_dt: new Date(),
  interval: '',
  remainder_inner: '',
  remainder_gold: '',
  no_login_days: '',
  jump_times: ''
}
export default {
  name: 'GrantAuto',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '待审核',
        1: '进行中',
        2: '暂停中',
        3: '已停止'
      }
      return statusMap[status]
    },
    statusTagFilter(status) {
      const statusTagMap = {
        0: 'primary',
        1: 'success',
        2: 'warning',
        3: 'info'
      }
      return statusTagMap[status]
    }
  },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      list: [],
      actorList: [],
      multipleSelection: [],
      total: 0,
      listLoading: false,
      disabled: false,
      dataForm: Object.assign({}, defaultItem),
      actorid: '',
      rules: {
        grant_num: [{ required: true, message: '请填写发放数量', trigger: 'blur' }],
        grant_dt: [{ required: true, message: '请填写发放时间', trigger: 'blur' }],
        interval: [{ required: true, message: '请填写间隔时间', trigger: 'blur' }],
        remainder_inner: [{ required: true, message: '请填写发放条件', trigger: 'blur' }],
        no_login_days: [{ required: true, message: '请填写停止条件', trigger: 'blur' }]
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      dialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      const query = this.listQuery
      this.listLoading = true
      const res = await getGrantJobList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.actor = this.actorList
          handleGrantJob(this.dataForm).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteGrantJob(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    handleChangeStatus(row, value) {
      handleGrantJobStatus({ status: value }, row.id).then(response => {
        this.getList()
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
      })
    },
    // 审核
    async pass(row) {
      if (this.multipleSelection.length <= 0 && typeof row === 'undefined') {
        this.$message.error('请至少选择一条未审核的记录')
        return false
      }

      this.$confirm('你确定审核吗?', '高风险操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.disabled = true
        const d = this.multipleSelection
        if (row) {
          d.push(row)
        }
        approvedJob(d).then(response => {
          this.disabled = false
          this.multipleSelection = []
          if (response.status === true) {
            this.$message.success('操作成功!')
            this.getList()
          } else {
            this.$message.error('操作失败!')
          }
        })
      }).catch(err => {
        console.error(err)
      })
    },
    handleBlueActorId() {
      if (this.actorid === '' || this.actorid === undefined) return false
      checkActor({ actor_id: this.actorid }).then(response => {
        if (response.status) {
          this.actorList = response.data
        }
      })
    },
    cellClassNameFn(row) {
      if (row.columnIndex === 0 && row.row.status === 1) {
        return 'table-column-hidden'
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}

</script>
<style>
.text30 {
  width: 30%;
}
</style>
